import copy
from copy import deepcopy
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

new_personal_event_project_v2_api = Blueprint('new_personal_event_project_v2_api', __name__)
new_personal_event_project_v2_down_api = Blueprint('new_personal_event_project_v2_down_api', __name__)


def get_doc_file(field):
    with open(GLOBAL_PATH + 'operation_event_english.json', encoding='utf8') as f:
        data = json.load(f)
    if field in data:
        return data[field]
    else:
        return {}


@new_personal_event_project_v2_api.route('/new_personal_event_project_v2', methods=['POST'])
def new_personal_event_project_v2():
    params = json.loads(request.data)
    _action = params['action']
    _project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if _action == 'view':
        query = NewPersonalEventProjectV2.query.order_by('project').all()
        result = []
        for q in query:
            localization = json.loads(q.localization)
            if "1" in localization:
                title = localization["1"]["title"]
            else:
                title = ''

            tmp = {
                "project": int(q.project),
                'title': title,
                'remark': q.remark
            }
            result.append(tmp)
        result_data['data']['item'] = result
    elif _action == 'detail':
        query = NewPersonalEventProjectV2.query.filter_by(project=_project).first()
        basic = json.loads(query.basic)
        if 'calendar_reward' not in basic:
            basic['calendar_reward'] = []
        if '_tag' not in basic:
            basic['_tag'] = []

        tmp = {
            "project": int(query.project),
            'basic': basic,
            'reward': json.loads(query.reward)
        }
        result_data['data']['item'] = tmp
    elif _action == 'update_part':
        _data = params['data']
        _part = params['part']
        '''daily_deals_event_project_data = DailyDealsEventProject.query.filter_by(project=_project).first()
        reward = json.loads(daily_deals_event_project_data.reward)'''
        if _part == 'basic':
            NewPersonalEventProjectV2.query.filter_by(project=_project).update({
                'basic': json.dumps(_data)
            })
        elif _part == 'goal_reward':
            new_personal_event_project_v2_data = NewPersonalEventProjectV2.query.filter_by(project=_project).first()
            reward = json.loads(new_personal_event_project_v2_data.reward)
            reward["goal_reward"] = _data
            NewPersonalEventProjectV2.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        elif _part == 'rank_reward':
            new_personal_event_project_v2_data = NewPersonalEventProjectV2.query.filter_by(project=_project).first()
            reward = json.loads(new_personal_event_project_v2_data.reward)
            reward["rank_reward"] = _data
            NewPersonalEventProjectV2.query.filter_by(project=_project).update({
                'reward': json.dumps(reward)
            })
        db.session.commit()
        result_data['data']['msg'] = "更新成功"
    elif _action == 'remark':
        newRemark = params['remark']
        NewPersonalEventProjectV2.query.filter_by(project=_project).update({'remark': newRemark})
        db.session.commit()
        result_data['data']['msg'] = "Remark 更新成功"
    elif _action == 'clone':  # 克隆方案
        new_personal_event_project_v2_data = NewPersonalEventProjectV2.query.filter_by(project=_project).first()
        new_project_data = NewPersonalEventProjectV2(
            basic=new_personal_event_project_v2_data.basic,
            localization=new_personal_event_project_v2_data.localization,
            reward=new_personal_event_project_v2_data.reward,
            remark=new_personal_event_project_v2_data.remark
        )
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if new_project_id is None:
            result_data['status'] = 500
            result_data['data']['msg'] = "克隆失败：id is None"
        else:
            result_data['data']['msg'] = "克隆成功"
    elif _action == 'delete':
        new_personal_event_project_v2_data = NewPersonalEventProjectV2.query.filter_by(project=_project).first()
        db.session.delete(new_personal_event_project_v2_data)
        db.session.commit()
        new_personal_event_project_v2_data = NewPersonalEventProjectV2.query.filter_by(project=_project).first()
        if new_personal_event_project_v2_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败：id is not None"
        else:
            result_data['data']['msg'] = "删除成功"
    elif _action == 'iap_list':
        with open(STATIC_PATH + 'iap_list.json') as f:
            data = json.load(f)
            for i in data:
                i['value'] = i['gem']
                i['label'] = i['label'] + ' - ' + str(i['gem'])
            return json.dumps(data)
    elif _action == 'score_list':
        with open(STATIC_PATH + 'new_personal_event_task_pool.json', encoding='UTF-8') as f:
            data = json.load(f)
            _result = []
            for i in data:
                _condition = '无条件'
                if len(i['show']) > 0:
                    if i['show'][0]['type'] == 1:
                        _condition = '满研究'
                _result.append({
                    "value": i['idx'],
                    "label": str(i['idx']) + '-' + i['label'] + '-' + _condition
                })
            return json.dumps(_result)
    elif _action == 'doc_id_list':
        doc_file_data = get_doc_file('new_personal_event')
        result = []
        for i in doc_file_data:
            result.append({
                'value': int(i),
                'label': f'{i} - {doc_file_data[i]["title"]}'
            })
        return json.dumps(result)
    return jsonify(result_data)


@new_personal_event_project_v2_down_api.route('/new_personal_event_project_v2_down/<int:is_push>', methods=['GET', 'POST'])
def new_personal_event_project_v2_down(is_push):
    def get_reward_info(r):
        t = {"a": [r['type'], r['id'], r['num']]}
        return t
    def get_reward_list(a):
        tmp_reward = []
        for i in range(0, len(a)):
            for j in range(0, len(a[i]['reward'])):
                tmp_reward.append(get_reward_info(a[i]['reward'][j]))
        return tmp_reward

    result = {}

    query = NewPersonalEventProjectV2.query.order_by('project').all()

    for q in query:
        _project = str(q.project)
        basic = json.loads(q.basic)
        reward_data = json.loads(q.reward)
        localization = json.loads(q.localization)
        _calc_score = []
        with open(STATIC_PATH + 'new_personal_event_task_pool.json', encoding='UTF-8') as f:
            data = json.load(f)
            for i in basic['calc_score']:
                for j in data:
                    if j['idx'] == i:
                        temp = copy.deepcopy(j)
                        if 'idx' in temp:
                            del temp['idx']
                        if 'label' in temp:
                            del temp['label']
                        _calc_score.append(temp)

        _temp_goal = []
        for i in range(0, len(reward_data["goal_reward"])):
            _temp_goal.append({
                "from": 1,
                "to": reward_data["goal_reward"][i]["to"],
                "reward": RewardToTMysqlNew(reward_data["goal_reward"][i]["reward"]),
                "doc_id": 94936
            })
        _temp_rank = []
        for i in range(0, len(reward_data["rank_reward"])):
            if reward_data["rank_reward"][i]["from"] == reward_data["rank_reward"][i]["to"]:
                _doc_id = 94920
            else:
                _doc_id = 94921
            _temp_rank.append({
                "from": reward_data["rank_reward"][i]["from"],
                "to": reward_data["rank_reward"][i]["to"],
                "reward": RewardToTMysqlNew(reward_data["rank_reward"][i]["reward"]),
                "doc_id": _doc_id
            })

        if 'calendar_reward' in basic:
            calendar_reward = RewardToTMysqlNew(basic['calendar_reward'])
        else:
            calendar_reward = []

        # 20221115 文案分离
        if 'doc_id' in basic:
            doc_id = basic['doc_id']
        else:
            doc_id = 1

        # if 'calendar_doc_id' in basic:
        #     _calendar_doc_id = basic['calendar_doc_id']
        # else:
        #     _calendar_doc_id = 1
        # 20221128 优化将活动日历的doc_id改为与活动文案doc_id一致

        _tag = basic['_tag'] if '_tag' in basic else []

        tmp = {
            '_tag': _tag,
            'calendar_conf': {
                'event_type': 97,
                'event_ui': basic['event_ui'],
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': doc_id,
                    'info': doc_id
                },
                'reward': calendar_reward,
                'show_type': 0
            },
            "basic": {
                "event_ui": basic['event_ui']
            },
            "localization_str": localization,
            "localization_doc": {
                'title': doc_id,
                'info': doc_id,
                'content': doc_id,
                'help_info': doc_id
            },
            "calc_score": {
                "score_type_list": _calc_score
            },
            "reward": {
                "goal_reward": {
                    "user": _temp_goal
                },
                "rank_reward": {
                    "user": _temp_rank
                }
            },
            "extern0": {
                "rank_limit": basic["rank_limit"]
            },
            "extern1": {},
            "remark": q.remark
        }
        result[_project] = tmp

    response = DownLoad('new_personal_event_project_v2', result, is_push)

    return response
